//
//  YCPhotoLibraryManager.swift
//  YCCamera
//
//  Created by Billy on 2024/11/6.
//

import UIKit
import Photos
import UniformTypeIdentifiers

class YCPhotoLibraryManager {
    
    // MARK: - Properties
    private var cachedLatestPhotoId: String?
    private var imageRequestId: PHImageRequestID?
    
    // MARK: - Get Latest Photo
    
    /// 获取相册最新的照片缩略图
    func getLatestPhoto(completion: @escaping (UIImage?) -> Void) {
        // 取消任何正在进行的请求
        if let requestId = imageRequestId {
            PHImageManager.default().cancelImageRequest(requestId)
        }
        
        PHPhotoLibrary.requestAuthorization { [weak self] status in
            guard let self = self, status == .authorized else {
                DispatchQueue.main.async {
                    completion(nil)
                }
                return
            }
            
            let fetchOptions = PHFetchOptions()
            fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
            fetchOptions.fetchLimit = 1
            
            let fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
            
            guard let latestPhoto = fetchResult.firstObject else {
                DispatchQueue.main.async {
                    completion(nil)
                }
                return
            }
            
            // 检查是否已缓存同一照片
            if self.cachedLatestPhotoId == latestPhoto.localIdentifier {
                return // 已经有最新照片，不需要重新加载
            }
            
            // 更新缓存ID
            self.cachedLatestPhotoId = latestPhoto.localIdentifier
            
            // 配置请求选项
            let option = PHImageRequestOptions()
            option.isNetworkAccessAllowed = true
            option.deliveryMode = .highQualityFormat
            option.resizeMode = .exact
            option.isSynchronous = false
            option.version = .current
            
            // 请求缩略图
            self.imageRequestId = PHImageManager.default().requestImage(
                for: latestPhoto,
                targetSize: YCCameraConstants.PhotoLibrary.thumbnailSize,
                contentMode: .aspectFill,
                options: option
            ) { (image, info) in
                guard let thumbnail = image else {
                    DispatchQueue.main.async {
                        completion(nil)
                    }
                    return
                }
                
                // 检查是否是最终图像而非降级版本
                let isDegraded = (info?[PHImageResultIsDegradedKey] as? Bool) ?? false
                
                if !isDegraded {
                    DispatchQueue.main.async {
                        completion(thumbnail)
                    }
                }
            }
        }
    }
    
    /// 强制刷新缓存（用于拍照后更新）
    func invalidateCache() {
        cachedLatestPhotoId = nil
    }
    
    // MARK: - Save Photo with Metadata
    
    /// 保存照片到相册（带完整元数据）
    func savePhotoWithMetadata(
        _ image: UIImage,
        flashOn: Bool,
        device: AVCaptureDevice?,
        completion: @escaping (Bool, Error?) -> Void
    ) {
        // 创建临时文件URL
        let temporaryDir = FileManager.default.temporaryDirectory
        let temporaryFileURL = temporaryDir.appendingPathComponent(UUID().uuidString + ".jpg")
        
        // 准备元数据
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy:MM:dd HH:mm:ss"
        let currentDate = dateFormatter.string(from: Date())
        
        // 创建TIFF字典
        let tiffDict: [String: Any] = [
            kCGImagePropertyTIFFMake as String: "Apple",
            kCGImagePropertyTIFFModel as String: UIDevice.current.modelName,
            kCGImagePropertyTIFFSoftware as String: "iOS \(UIDevice.current.systemVersion)",
            kCGImagePropertyTIFFDateTime as String: currentDate,
            kCGImagePropertyTIFFOrientation as String: "\(NSNumber(value: image.imageOrientation.rawValue))",
            kCGImagePropertyTIFFPhotometricInterpretation as String: "2",
            kCGImagePropertyTIFFCompression as String: "6",
            kCGImagePropertyTIFFResolutionUnit as String: "2",
            kCGImagePropertyTIFFXResolution as String: "72",
            kCGImagePropertyTIFFYResolution as String: "72"
        ]
        
        // 创建EXIF字典
        var exifDictionary: [String: Any] = [
            kCGImagePropertyExifDateTimeOriginal as String: currentDate,
            kCGImagePropertyExifFlash as String: NSNumber(value: flashOn ? 1 : 0)
        ]
        
        // 添加设备信息到EXIF
        if let device = device {
            do {
                try device.lockForConfiguration()
                exifDictionary[kCGImagePropertyExifISOSpeedRatings as String] = [NSNumber(value: Int(device.iso))]
                exifDictionary[kCGImagePropertyExifFNumber as String] = NSNumber(value: Float(device.lensAperture))
                exifDictionary[kCGImagePropertyExifFocalLength as String] = NSNumber(value: Float(device.activeFormat.videoFieldOfView))
                exifDictionary[kCGImagePropertyExifExposureTime as String] = NSNumber(value: CMTimeGetSeconds(device.exposureDuration))
                exifDictionary[kCGImagePropertyExifExposureBiasValue as String] = NSNumber(value: device.exposureTargetBias)
                device.unlockForConfiguration()
            } catch {
                print("设备配置锁定失败: \(error.localizedDescription)")
            }
        }
        
        // 保存图片和元数据
        guard let cgImage = image.cgImage else {
            completion(false, NSError(domain: "YCPhotoLibraryManager", code: -1, userInfo: [NSLocalizedDescriptionKey: "无法获取CGImage"]))
            return
        }
        
        print("💾 保存照片 - UIImage.size: \(image.size.width)x\(image.size.height), scale: \(image.scale)")
        print("💾 保存照片 - CGImage: \(cgImage.width)x\(cgImage.height)")
        
        guard let destination = CGImageDestinationCreateWithURL(
            temporaryFileURL as CFURL,
            UTType.jpeg.identifier as CFString,
            1,
            nil
        ) else {
            completion(false, NSError(domain: "YCPhotoLibraryManager", code: -2, userInfo: [NSLocalizedDescriptionKey: "无法创建图像目标"]))
            return
        }
        
        // 合并所有元数据
        let metadata: [String: Any] = [
            kCGImagePropertyTIFFDictionary as String: tiffDict,
            kCGImagePropertyExifDictionary as String: exifDictionary,
            kCGImagePropertyOrientation as String: NSNumber(value: image.imageOrientation.rawValue)
        ]
        
        // 写入图片和元数据
        CGImageDestinationAddImage(destination, cgImage, metadata as CFDictionary)
        
        guard CGImageDestinationFinalize(destination) else {
            try? FileManager.default.removeItem(at: temporaryFileURL)
            completion(false, NSError(domain: "YCPhotoLibraryManager", code: -3, userInfo: [NSLocalizedDescriptionKey: "无法写入图片元数据"]))
            return
        }
        
        // 保存到相册
        guard let imageDataWithMetadata = try? Data(contentsOf: temporaryFileURL) else {
            try? FileManager.default.removeItem(at: temporaryFileURL)
            completion(false, NSError(domain: "YCPhotoLibraryManager", code: -4, userInfo: [NSLocalizedDescriptionKey: "无法读取图片数据"]))
            return
        }
        
        PHPhotoLibrary.shared().performChanges {
            let options = PHAssetResourceCreationOptions()
            options.shouldMoveFile = false
            let creationRequest = PHAssetCreationRequest.forAsset()
            creationRequest.addResource(with: .photo, data: imageDataWithMetadata, options: options)
        } completionHandler: { success, error in
            // 清理临时文件
            try? FileManager.default.removeItem(at: temporaryFileURL)
            
            if success {
                print("✅ 保存照片成功")
                // 清除缓存，以便下次获取最新照片
                self.invalidateCache()
            } else if let error = error {
                print("❌ 保存照片失败: \(error.localizedDescription)")
            }
            
            completion(success, error)
        }
    }
}

